package weapon

import (
    "cloud_worm/util/umodels/mysqldb"
    "cloud_worm/util/umodels/mysqldb/dbtask"
    "github.com/astaxie/beego/logs"
    "fmt"
    "strings"
    "time"
    "cloud_worm/util/uid"
    "cloud_worm/util/uconst"
    "cloud_worm/util/uhttp"
    "cloud_worm/wormweb/controllers/ctrconfig"
    "cloud_worm/wormweb/controllers/ctrutil"
)

type WpController struct {
    ctrconfig.LoginCtr
}

func (wp *WpController) List() {
    wp.Manager()

    offset, limit := wp.DealPage()
    status, err := wp.GetInt("status", mysqldb.StatusAll)
    name := wp.GetString("name")
    uploadUser := wp.GetString("upload_user")
    wpType, err := wp.GetInt("type", mysqldb.SelectIntAll)
    wpMode, err := wp.GetInt("mode", mysqldb.SelectIntAll)

    // 查询数据
    wpon := &dbtask.Weapon{}
    count, err := wpon.Count(status, name, uploadUser, wpType, wpMode)
    if err != nil {
        logs.Error(fmt.Sprintf("get weapon count error: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbtask.Weapon{}}
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "get count error.", data)
        wp.ServeJSON()
        return
    }
    wpons, err := wpon.Select(offset, limit, status, name, uploadUser, wpType, wpMode)
    if err != nil {
        logs.Error(fmt.Sprintf("get weapon error: %s", err.Error()))
        data := map[string]interface{}{"total": count, "data": []dbtask.Weapon{}}
        wp.Data["json"] = uhttp.CreateOkResponse(data)
        wp.ServeJSON()
        return
    }

    data := map[string]interface{}{"total": count, "data": wpons}
    wp.Data["json"] = uhttp.CreateOkResponse(data)
    wp.ServeJSON()
    return
}

func (wp *WpController) Insert()  {
    wp.Manager()

    type InputInfo struct {
        Name        string      `json:"name"`               // 必填
        Comment     string      `json:"comment"`            // 必填
        Parameters  string      `json:"parameters"`
        Md5         string      `json:"md5"`                // 必填
        TaskMode    int         `json:"task_mode"`
        Timeout     int         `json:"timeout"`
        Output      string      `json:"output"`
        Url         string      `json:"url"`                // 必填
        WpType      int         `json:"wp_type"`
    }
    var input InputInfo
    if err := wp.Unmarshal(&input); err != nil {
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, err.Error(), nil)
        wp.ServeJSON()
        return
    }

    if input.Name == mysqldb.SelectStrAll {
        logs.Error(fmt.Sprintf("input name error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input name error", nil)
        wp.ServeJSON()
        return
    }
    if input.Comment == mysqldb.SelectStrAll {
        logs.Error(fmt.Sprintf("input comment error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input comment error", nil)
        wp.ServeJSON()
        return
    }
    if len(input.Md5) != uconst.WpMd5Len {
        logs.Error(fmt.Sprintf("input md5 error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input md5 error", nil)
        wp.ServeJSON()
        return
    }

    if input.Timeout < uconst.TimeoutMin {
        input.Timeout = uconst.TimeoutDefault
    }
    if input.Url == "" || strings.HasSuffix(input.Url, input.Name) == false {
        logs.Error(fmt.Sprintf("input url error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input url error", nil)
        wp.ServeJSON()
        return
    }

    wpon := &dbtask.Weapon{
        Name: input.Name,
        Comment: input.Comment,
        Parameters: input.Parameters,
        Md5: input.Md5,
        TaskMode: input.TaskMode,
        Timeout: input.Timeout,
        Output: input.Output,
        Url: input.Url,
        Type: input.WpType,
        UploadUser: wp.UserInfo.Username,
        Created: time.Now().Unix(),
        Status: mysqldb.StatusValid,
    }
    wpon.Updated = wpon.Created
    wpon.Id = uid.IdDriver(ctrutil.WebIdcNum).GetNextId()
    if err := wpon.Insert(); err != nil {
        logs.Error(fmt.Sprintf("weapon insert error: %s", err.Error()))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "weapon insert error", nil)
        wp.ServeJSON()
        return
    }

    wp.Data["json"] = uhttp.CreateOkResponse(nil)
    wp.ServeJSON()
    return
}

// 更新weapon信息
func (wp *WpController) Update() {
    wp.Manager()

    type InputInfo struct {
        Id          int64       `json:"id"`
        Name        string      `json:"name"`               // 必填
        Comment     string      `json:"comment"`            // 必填
        Parameters  string      `json:"parameters"`
        Md5         string      `json:"md5"`                // 必填
        TaskMode    int         `json:"task_mode"`
        Timeout     int         `json:"timeout"`
        Output      string      `json:"output"`
        Url         string      `json:"url"`                // 必填
        WpType      int         `json:"wp_type"`
        Status      int         `json:"status"`
    }
    var input InputInfo
    if err := wp.Unmarshal(&input); err != nil {
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, err.Error(), nil)
        wp.ServeJSON()
        return
    }

    if input.Name == mysqldb.SelectStrAll {
        logs.Error(fmt.Sprintf("input name error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input name error", nil)
        wp.ServeJSON()
        return
    }
    if input.Comment == mysqldb.SelectStrAll {
        logs.Error(fmt.Sprintf("input comment error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input comment error", nil)
        wp.ServeJSON()
        return
    }
    if len(input.Md5) != uconst.WpMd5Len {
        logs.Error(fmt.Sprintf("input md5 error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input md5 error", nil)
        wp.ServeJSON()
        return
    }

    if input.Timeout < uconst.TimeoutMin {
        input.Timeout = uconst.TimeoutDefault
    }
    if input.Url == "" || strings.HasSuffix(input.Url, input.Name) == false {
        logs.Error(fmt.Sprintf("input url error"))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input url error", nil)
        wp.ServeJSON()
        return
    }
    if input.Status != mysqldb.StatusValid && input.Status != mysqldb.StatusInvalid {
        logs.Error(fmt.Sprintf("input status error: %d", input.Status))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input status error", nil)
        wp.ServeJSON()
        return
    }

    wpon := &dbtask.Weapon{
        Id: input.Id,
        Name: input.Name,
    }
    if err := wpon.Read("id", "name"); err != nil {
        logs.Error(fmt.Sprintf("no this weapon error: %s", err.Error()))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "no this weapon for update", nil)
        wp.ServeJSON()
        return
    }
    wpon.Comment = input.Comment
    wpon.Parameters = input.Parameters
    wpon.Md5 = input.Md5
    wpon.TaskMode = input.TaskMode
    wpon.Timeout = input.Timeout
    wpon.Output = input.Output
    wpon.Url = input.Url
    wpon.Type = input.WpType
    wpon.UploadUser = wp.UserInfo.Username
    wpon.Updated = time.Now().Unix()
    wpon.Status = input.Status

    err := wpon.Update("comment", "parameters", "md5", "task_mode", "timeout", "output",
        "url", "type", "upload_user", "updated", "status")
    if err != nil {
        logs.Error(fmt.Sprintf("weapon update error: %s", err.Error()))
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "weapon update error", nil)
        wp.ServeJSON()
        return
    }

    wp.Data["json"] = uhttp.CreateOkResponse(nil)
    wp.ServeJSON()
    return
}

func (wp *WpController) Select()  {
    wp.Manager()

    id, err := wp.GetInt("id")
    if err != nil {
        logs.Warning(fmt.Sprintf("input id error: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbtask.Weapon{}}
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input id error", data)
        wp.ServeJSON()
        return
    }

    wpon := &dbtask.Weapon{Id: int64(id)}
    err = wpon.Read("id")
    if err != nil {
        logs.Warning(fmt.Sprintf("no this id record: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbtask.Weapon{}}
        wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "no input id record", data)
        wp.ServeJSON()
        return
    }

    var wpons []dbtask.Weapon
    wpons = append(wpons, *wpon)
    data := map[string]interface{}{"total": 1, "data": wpons}
    wp.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeOk, "no input id record", data)
    wp.ServeJSON()
    return
}

// WpTaskModeList 获取任务模式的列表
func (wp *WpController) WpTaskModeList() {
    wp.Manager()

    type TaskModeInfo struct {
        Name        string      `json:"name"`
        Value       int         `json:"value"`
    }

    tms := []TaskModeInfo{
        {
            Name: "ModeDefault",
            Value: dbtask.WeaponTaskModeDefault,
        },
        {
            Name: "ModeBaseSec",
            Value: dbtask.WeaponTaskModeBaseSec,
        },
    }

    data := map[string]interface{}{"total": len(tms), "data": tms}
    wp.Data["json"] = uhttp.CreateOkResponse(data)
    wp.ServeJSON()
    return
}

// WpTypeList weapon类型的list
func (wp *WpController) WpTypeList() {
    wp.Manager()

    type WpType struct {
        Name        string      `json:"name"`
        Value       int         `json:"value"`
    }

    wts := []WpType{
        {
            Name: "NeedAnalyzer",
            Value: dbtask.WeaponTypeNeedAnalyzer,
        },
        {
            Name: "NoAnalyzer",
            Value: dbtask.WeaponTypeNoAnalyzer,
        },
        {
            Name: "CareResult",
            Value: dbtask.WeaponTypeCareResult,
        },
    }

    data := map[string]interface{}{"total": len(wts), "data": wts}
    wp.Data["json"] = uhttp.CreateOkResponse(data)
    wp.ServeJSON()
    return
}
